/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.sys.web;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.Category;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.CategoryService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 机构Controller
 * @author ThinkGem
 * @version 2013-5-15
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/category")
public class CategoryController extends BaseController {

	@Autowired
	private CategoryService categoryService;
	
	@ModelAttribute("category")
	public Category get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return categoryService.get(id);
		}else{
			return new Category();
		}
	}

	@RequiresPermissions("sys:category:view")
	@RequestMapping(value = {""})
	public String index(Category category, Model model) {
//        model.addAttribute("list", officeService.findAll());
		return "modules/sys/categoryIndex";
	}

	@RequiresPermissions("sys:category:view")
	@RequestMapping(value = {"list"})
	public String list(Category category, Model model) {
        model.addAttribute("list", categoryService.findList(category));
		return "modules/sys/categoryList";
	}
	
	@RequiresPermissions("sys:category:view")
	@RequestMapping(value = "form")
	public String form(Category category, Model model) {
		User user = UserUtils.getUser();
//		if (category.getParent()==null || category.getParent().getId()==null){
//			category.setParent(user.getOffice());
//		}
		category.setParent(categoryService.get(category.getParent().getId()));
//		if (category.getArea()==null){
//			office.setArea(user.getOffice().getArea());
//		}
		// 自动获取排序号
		if (StringUtils.isBlank(category.getId())&&category.getParent()!=null){
			int size = 0;
			List<Category> list = categoryService.findAll();
			for (int i=0; i<list.size(); i++){
				Category e = list.get(i);
				if (e.getParent()!=null && e.getParent().getId()!=null
						&& e.getParent().getId().equals(category.getParent().getId())){
					size++;
				}
			}
			category.setCode(category.getParent().getCode() + StringUtils.leftPad(String.valueOf(size > 0 ? size+1 : 1), 3, "0"));
		}
		model.addAttribute("category", category);
		return "modules/sys/categoryForm";
	}
	
	@RequiresPermissions("sys:category:edit")
	@RequestMapping(value = "save")
	public String save(Category category, Model model, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/category/";
		}
		if (!beanValidator(model, category)){
			return form(category, model);
		}
		categoryService.save(category);
		
		if(category.getChildDeptList()!=null){
			Category childCategory = null;
			for(String id : category.getChildDeptList()){
				childCategory = new Category();
				childCategory.setName(DictUtils.getDictLabel(id, "sys_category_common", "未知"));
				childCategory.setParent(category);
				childCategory.setArea(category.getArea());
				childCategory.setType("2");
				childCategory.setGrade(String.valueOf(Integer.valueOf(category.getGrade())+1));
				childCategory.setUseable(Global.YES);
				categoryService.save(childCategory);
			}
		}
		
		addMessage(redirectAttributes, "保存项目层级'" + category.getName() + "'成功");
		String id = "0".equals(category.getParentId()) ? "" : category.getParentId();
		return "redirect:" + adminPath + "/sys/category/list?id="+id+"&parentIds="+category.getParentIds();
	}
	
	@RequiresPermissions("sys:category:edit")
	@RequestMapping(value = "delete")
	public String delete(Category category, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/category/list";
		}
//		if (Office.isRoot(id)){
//			addMessage(redirectAttributes, "删除机构失败, 不允许删除顶级机构或编号空");
//		}else{
			categoryService.delete(category);
			addMessage(redirectAttributes, "删除项目层级成功");
//		}
		return "redirect:" + adminPath + "/sys/category/list?id="+category.getParentId()+"&parentIds="+category.getParentIds();
	}

	/**
	 * 获取机构JSON数据。
	 * @param extId 排除的ID
	 * @param type	类型（1：公司；2：部门/小组/其它：3：用户）
	 * @param grade 显示级别
	 * @param response
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId, @RequestParam(required=false) String type,
			@RequestParam(required=false) Long grade, @RequestParam(required=false) Boolean isAll, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Category> list = categoryService.findList(isAll);
		for (int i=0; i<list.size(); i++){
			Category e = list.get(i);
			/*if ((StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1))
					&& (type == null || (type != null && (type.equals("1") ? type.equals(e.getType()) : true)))
					&& (grade == null || (grade != null && Integer.parseInt(e.getGrade()) <= grade.intValue()))
					&& Global.YES.equals(e.getUseable())){*/
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("pIds", e.getParentIds());
				map.put("name", e.getName());
				if (type != null && "3".equals(type)){
					map.put("isParent", true);
				}
				mapList.add(map);
//			}
		}
		return mapList;
	}
}
